package ro.dandanciu.webgallery.ui.galleries;

import java.io.File;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;

import ro.dandanciu.webgallery.domainmodel.Gallery;
import ro.dandanciu.webgallery.exceptions.ApplicationException;
import ro.dandanciu.webgallery.exceptions.GenericUploadException;
import ro.dandanciu.webgallery.exceptions.IllegalContentTypeException;
import ro.dandanciu.webgallery.services.ImageServices;
import ro.dandanciu.webgallery.ui.general.WebGalleryAction;

public class GalleryUploadAction extends WebGalleryAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(GalleryUploadAction.class);

	/**
	 * 
	 */
	private static final long serialVersionUID = 8222604444042363505L;
	
	private String mode ="";
	
	private final static String UPLOAD_MODE = "UPLOAD";
	
	private ImageServices imageServices;

	private long galleryId;

	public GalleryUploadAction(ImageServices imageServices) {
		this.imageServices = imageServices;
	}
	
	
	public String execute() throws Exception {

		
		if (logger.isDebugEnabled()) {
			logger.debug("execute() - start");
		}

		String forward = "message";

		if (UPLOAD_MODE.equals(mode)) {
			executeUpload();
		} else {
			setMessage("failure");
		}
	
		if (logger.isDebugEnabled()) {
			logger.debug("forward: " + forward);
			logger.debug("execute() - end");
		}
		return forward;
	}

	private void executeUpload() {

		try {
			MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) ServletActionContext
					.getRequest();
			if (multiWrapper.hasErrors()) {
				throw new GenericUploadException();
			}

			File file = multiWrapper.getFiles("uploadedFile")[0];
			String name = multiWrapper.getFileNames("uploadedFile")[0];
			String contentType = multiWrapper.getContentTypes("uploadedFile")[0];

			if (!contentType.startsWith("image")) {
				throw new IllegalContentTypeException();
			}

			Gallery gallery = galleryServices.getGalleryById(galleryId);
			imageServices.add(file, gallery, name, contentType);
			setMessage("gallery.upload.success");
		} catch (IllegalContentTypeException e) {
			setMessage("gallery.upload.illegalContentType");
		} catch (GenericUploadException e) {
			setMessage("gallery.upload.problem");
		} catch (ApplicationException e) {
			setMessage("failure");
		}
	}

	public String getMode() {
		return mode;
	}

	public void setMode(String mode) {
		this.mode = mode;
	}

	public long getGalleryId() {
		return galleryId;
	}

	public void setGalleryId(long galleryId) {
		this.galleryId = galleryId;
	}
	
	

}
